<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>财务管理</title>
		<meta name="renderer" content="webkit" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
		<link rel="stylesheet" href="/lib/layui/css/layui.css" media="all" />
		<link rel="stylesheet" href="/css/public.css" media="all" />
	</head>

	<body>
		<div class="layuimini-container">
			<div class="layuimini-main">
				<!-- 搜索条件 -->
				<fieldset class="table-search-fieldset">
					<legend>搜索信息</legend>
					<div style="margin: 10px 10px 10px 10px">
						<form class="layui-form layui-form-pane" action="">
						<div class="layui-form-item">
							<div class="layui-inline">
								<label class="layui-form-label">用户ID</label>
								<div class="layui-input-inline">
									<input type="text" name="userId" placeholder="请输入用户ID" autocomplete="off" class="layui-input" />
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">用户名</label>
								<div class="layui-input-inline">
									<input type="text" name="userName" placeholder="请输入用户名" autocomplete="off" class="layui-input" />
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">操作类型</label>
								<div class="layui-input-inline">
									<select name="transactionType" lay-search>
										<option value="">请选择类型</option>
										<option value="后台充值">后台充值</option>
										<option value="后台赠送">后台赠送</option>
										<option value="后台扣款">后台扣款</option>
									</select>
								</div>
							</div>
							<div class="layui-inline">
								<label class="layui-form-label">操作员</label>
								<div class="layui-input-inline">
									<input type="text" name="operator" placeholder="请输入操作员" autocomplete="off" class="layui-input" />
								</div>
							</div>
							
							<div class="layui-inline">
							<label class="layui-form-label">备注/原因</label>
							<div class="layui-input-inline">
								<input type="text" name="remark" placeholder="请输入备注或操作原因" autocomplete="off" class="layui-input" />
							</div>
						</div>
						<div class="layui-inline" id="deletedStatusFilter" style="display: none;">
							<label class="layui-form-label">记录状态</label>
							<div class="layui-input-inline">
								<select name="isDeleted" lay-search>
									<option value="">全部</option>
									<option value="false">正常</option>
									<option value="true">已删除</option>
								</select>
							</div>
						</div>
							<div class="layui-inline">
								<label class="layui-form-label">创建时间</label>
								<div class="layui-input-inline">
									<input type="text" name="startTime" id="startTime" placeholder="开始日期" autocomplete="off" class="layui-input" />
								</div>
								<div class="layui-form-mid">-</div>
								<div class="layui-input-inline">
									<input type="text" name="endTime" id="endTime" placeholder="结束日期" autocomplete="off" class="layui-input" />
								</div>
							</div>
							<div class="layui-inline">
								<button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
							</div>
						</div>
					</form>
					</div>
				</fieldset>

				<script type="text/html" id="toolbarDemo">
					<div class="layui-btn-container">
						<!-- 移除批量删除按钮 -->
					</div>
				</script>

				<table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

				<script type="text/html" id="currentTableBar">
					{{# if(d.isAdmin) { }}
						<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">修改备注</a>
						<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
					{{# } else { }}
						<span style="color: #999;">仅可查看</span>
					{{# } }}
				</script>

				<script type="text/html" id="typeTpl">
					{{# if(d.type === '充值') { }}
					<span class="layui-badge layui-bg-green">充值</span>
					{{# } else if(d.type === '消费') { }}
					<span class="layui-badge layui-bg-red">消费</span>
					{{# } else if(d.type === '退款') { }}
					<span class="layui-badge layui-bg-blue">退款</span>
					{{# } else if(d.type === '奖励') { }}
					<span class="layui-badge layui-bg-orange">奖励</span>
					{{# } else if(d.type === '扣除') { }}
					<span class="layui-badge layui-bg-gray">扣除</span>
					{{# } }}
				</script>

				<script type="text/html" id="amountTpl">
					{{# if(d.type === '充值' || d.type === '奖励' || d.type === '退款') { }}
					<span style="color: #5FB878;">+¥{{(d.amount / 100).toFixed(2)}}</span>
					{{# } else { }}
					<span style="color: #FF5722;">-¥{{(d.amount / 100).toFixed(2)}}</span>
					{{# } }}
				</script>
			</div>
		</div>
		<script src="/lib/layui/layui.js" charset="utf-8"></script>
		<script src="/lib/axios/axios.js" charset="utf-8"></script>
		<script src="/lib/dayjs.js" charset="utf-8"></script>
		<script>
			layui.use(['form', 'table', 'laydate'], function () {
				var $ = layui.jquery,
					form = layui.form,
					table = layui.table,
					laydate = layui.laydate;

				// 从localStorage获取当前用户信息
			var userName = localStorage.getItem('userName');
			if (userName) {
				window.currentUser = { userName: userName };
				// 如果是cjroot管理员，显示删除状态筛选器
				if (userName === 'cjroot') {
					var deletedStatusFilter = document.getElementById('deletedStatusFilter');
					if (deletedStatusFilter) {
						deletedStatusFilter.style.display = 'block';
						form.render('select'); // 重新渲染select组件
					}
				}
			} else {
				console.log('未找到用户信息，请重新登录');
			}
			// 初始化表格
			initTable();

				// 日期选择器
				laydate.render({
					elem: '#startTime',
				});
				laydate.render({
					elem: '#endTime',
				});

				// 声明表格实例变量
				var tableIns;

				// 初始化表格函数
				function initTable() {
					// 获取当前用户信息
					var currentUser = localStorage.getItem('userName');
					var isAdmin = currentUser === 'cjroot';
					
					// 基础列配置
					var baseCols = [
						{ field: 'transactionId', width: 150, title: '流水号', sort: true },
						{
							field: 'orderNumber',
							width: 180,
							title: '订单号/批次号',
							sort: true,
							templet: function (d) {
								if (d.orderNumber) {
									return d.orderNumber;
								} else {
									return '-';
								}
							}
						},
						{
							field: 'userId',
							title: '用户ID',
							sort: true,
							templet: function (d) {
								return d.userId && d.userId._id ? d.userId._id : d.userId;
							},
						},
						{ field: 'userName', title: '用户名', sort: true },
						{ field: 'transactionType', title: '操作类型', sort: true },
						{
							field: 'amount',
							title: '金额',
							sort: true,
							templet: function (d) {
								var amount = (d.amount / 100).toFixed(2);
								if (d.amount > 0) {
									return '<span style="color: #5FB878;">+¥' + amount + '</span>';
								} else {
									return '<span style="color: #FF5722;">-¥' + Math.abs(amount) + '</span>';
								}
							},
						},
						{
							field: 'balanceBefore',
							title: '变动前余额',
							sort: true,
							templet: function (d) {
								return '¥' + (d.balanceBefore / 100).toFixed(2);
							},
						},
						{
							field: 'balanceAfter',
							title: '变动后余额',
							sort: true,
							templet: function (d) {
								return '¥' + (d.balanceAfter / 100).toFixed(2);
							},
						},
						{ field: 'operator', title: '操作员', sort: true }
					];
					
					// 管理员才显示备注和状态列
					if (isAdmin) {
						baseCols.push({ field: 'remark', minWidth: 200, title: '备注/操作原因', sort: true });
						baseCols.push({
							field: 'isDeleted',
							width: 80,
							title: '状态',
							templet: function (d) {
								if (d.isDeleted) {
									return '<span style="color: #ff5722;">已删除</span>';
								} else {
									return '<span style="color: #009688;">正常</span>';
								}
							},
						});
					}
					
					// 添加创建时间列
					baseCols.push({
						field: 'createTime',
						title: '创建时间',
						sort: true,
						templet: function (d) {
							return dayjs(d.createTime).format('YYYY-MM-DD HH:mm:ss');
						},
					});
					
					// 添加操作列
					baseCols.push({ title: '操作', width: 150, toolbar: '#currentTableBar', align: 'center' });
					
					tableIns = table.render({
					elem: '#currentTableId',
					url: '/balanceRecord/list',
					toolbar: '#toolbarDemo',
					cols: [baseCols],
					limits: [50, 200, 1000, 2000, 5000],
				limit: 50,
				page: true,
				parseData: function(res) {
						console.log('解析数据，当前用户:', window.currentUser);
						// 为每行数据添加管理员标识
						if (res.data && window.currentUser) {
							res.data.forEach(function(item) {
								item.isAdmin = window.currentUser.userName === 'cjroot';
								console.log('设置isAdmin:', item.isAdmin, '用户名:', window.currentUser.userName);
							});
						}
						return res;
					},
				done: function(res, curr, count) {
						console.log('表格渲染完成');
						// 如果是管理员，显示管理按钮
						if (window.currentUser && window.currentUser.userName === 'cjroot') {
							var adminButtons = document.getElementById('adminButtons');
							if (adminButtons) {
								adminButtons.style.display = 'block';
							}
						}
				}
			});

				// 监听搜索操作
				form.on('submit(data-search-btn)', function (data) {
					var result = JSON.stringify(data.field);
					tableIns.reload({
						where: data.field,
						page: {
							curr: 1,
						},
					});
					return false;
				});

				// 工具栏事件
				table.on('toolbar(currentTableFilter)', function (obj) {
					// 移除批量删除功能
				});

				// 监听行工具事件
				table.on('tool(currentTableFilter)', function (obj) {
					const data = obj.data;
					if (obj.event === 'edit') {
						layer.prompt(
							{
								title: '修改备注',
								formType: 2, // 多行文本框
								value: data.remark || '', // 默认值
								area: ['400px', '200px'],
							},
							function (value, index, elem) {
								axios
									.put('/balanceRecord/update/' + data._id, { remark: value.trim() })
									.then(function (res) {
										layer.close(index);
										tableIns.reload();
										layer.msg('更新成功！');
									})
									.catch(function (err) {
										console.log('请求失败', err.response || err);
										layer.alert(err.response?.data?.message || '请求失败');
									});
							},
						);
					} else if (obj.event === 'delete') {
						layer.confirm('确定要删除这条记录吗？', function (index) {
							axios
								.delete('/balanceRecord/delete/' + data._id)
								.then(function (res) {
									layer.close(index);
									tableIns.reload();

									layer.msg('删除成功！');
								})
								.catch(function (err) {
									layer.msg('删除失败');
								});
					});
				}
			});
			} // initTable函数结束
		});
	</script>
	</body>
</html>
